﻿using IGrain;
using Orleans;
using Orleans.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Client
{
    class Program
    {
        static int Main(string[] args)
        {
            return Run().Result;
        }

        static async Task<int> Run()
        {
            try
            {
                using (var client = await ConnectClient())
                {
                    await TestEmployee(client);
                }

                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine($"\nException while trying to run client: {e.Message}");
                Console.WriteLine("Make sure the silo the client is trying to connect to is running.");
                return 1;
            }

        }

        private static async Task TestEmployee(IClusterClient client)
        {
            var e1 = client.GetGrain<IEmployee>(Guid.NewGuid());
            var e2 = client.GetGrain<IEmployee>(Guid.NewGuid());
            var e3 = client.GetGrain<IEmployee>(Guid.NewGuid());

            var m1id = Guid.NewGuid();
            var m1 = client.GetGrain<IManager>(m1id);
            Console.WriteLine($"m1#Primaykey: {m1id}");

            var m1e = m1.AsEmployee().Result;
            await m1e.Promote(10);

            await e1.SetManager(m1);
            await e2.SetManager(m1);
            await e3.SetManager(m1);

            await m1.AddDirectReport(e1);
            await m1.AddDirectReport(e2);
            await m1.AddDirectReport(e3);
        }

        private static async Task DoSayHello(IClusterClient client)
        {
            var basic = client.GetGrain<IBasic>(0);

            await basic.DelayMsg("DelayMsg");
            //var delayReplay = await basic.DelayMsg("DelayMsg.");
            //Console.WriteLine($"delayReplay: {delayReplay}");

            var replay = await basic.SayHello("SayHello.");
            Console.WriteLine($"replay: {replay}");
            
        }

        private static async Task<IClusterClient> ConnectClient()
        {
            IClusterClient client;
            client = new ClientBuilder()
                .UseLocalhostClustering()
                .Configure<ClusterOptions>(options =>
                {
                    options.ClusterId = "dev";
                    options.ServiceId = "OrleansBasics";
                })
                .Build();

            await client.Connect();
            Console.WriteLine("Client successfully connected to silo host \n");
            return client;
        }
    }
}
